package pop3Server;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import dao.MailSendDAO;
import dao.UserDAO;

public class ReadSession extends Thread{
	
	private Socket client;
	private PrintWriter pw;
	private BufferedReader br;
	private String str=null;
	private String strr=null;
	private String UserName=null;
	private String UserPass=null;
	private String fileName=null;
	private UserDAO udao=new UserDAO();
	private MailSendDAO mdao=new MailSendDAO();
	private String ss[]=new String[100];
	private List<String> list=new ArrayList<String>();
	public static String basePath="D:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/mailSystem/AllUsers";

    public ReadSession(){
		
	}
    
	public ReadSession(Socket client){
		this.client=client;
		this.start();
	}
	
	public void run(){
		try {
			pw=new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
			br=new BufferedReader(new InputStreamReader(client.getInputStream()));
			printlnn("+OK Welcome to coremail Mail Pop3 Server ");
			this.service();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void service(){
		int step=1;
		try {
			while(true){
				str=br.readLine();
				if(null!=str){
					strr=str.toUpperCase();
				}else{
					strr="error";
				}
				if(strr.startsWith("USER ")&&step==1){
					int begin=str.indexOf(" ");
					UserName=str.substring(begin+1);
					if(udao.findByName(UserName)){
						printlnn("+OK core mail");
						step=2;
					}else{
						printlnn("No Such User Here!");
					}
				}else if(strr.startsWith("PASS ")&&step==2){
					int begin=str.indexOf(" ");
					UserPass=str.substring(begin+1);
					if(udao.findUser(UserName,UserPass)){
						list=getFilesList();
//						printlnn("+OK "+list.size()+" message(s)");
						printlnn("+OK 2 message(s)");
						step=3;
						break;
					}else{
						printlnn("No Such User Here!");
					}
				
				}else if(strr.startsWith("QUIT")){
					printlnn("+OK cor mail");
					br.close();
					pw.close();
					client.close();
					break;
				}else{
					printlnn("551 error");
				}
			}
			
			pw=new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
			br=new BufferedReader(new InputStreamReader(client.getInputStream()));
			while(true){
				str=br.readLine();
				if(null!=str){
					strr=str.toUpperCase();
				}else{
					strr="error";
				}
				if(strr.startsWith("STAT")&&step==3){
					printlnn("+OK 2 3561");
					step=4;
				}else if(strr.startsWith("LIST")&&step==4){
					printlnn("+OK 2 3561");
					
					int i=1;
					for(String s:list){
						ss[i]=s;
						File file=new File(basePath+"/"+UserName+"/receive/"+s);
						printlnn(i+" "+file.length());
						i++;
					}
					printlnn(".");
					step=5;
					break;
				}else if(strr.startsWith("QUIT")){
					printlnn("+OK cor mail");
					pw.close();
					br.close();
					client.close();
					break;
				}else{
					printlnn("551 error");
				}
				
			}
			pw=new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
			br=new BufferedReader(new InputStreamReader(client.getInputStream()));
			
			while(true){
				str=br.readLine();
				if(null!=str){
					strr=str.toUpperCase();
				}else{
					strr="error";
				}
//				System.out.println(str);
				if(strr.startsWith("RETR ")&&step==5){
					int begin=str.indexOf(" ");
					String sub=str.substring(begin+1);
//					System.out.println(sub);
					if(sub.matches("\\d")){
						int readNum=Integer.parseInt(sub);
//						System.out.println("readNum="+readNum);
						if(readNum>=1&&readNum<=list.size()){
							printlnn("+OK 1735 octets");
							ReadMail read=new ReadMail();
							read.readMail(pw,fileName+"/"+ss[readNum]);
							int end=ss[readNum].indexOf(".");
							String date=ss[readNum].substring(0,end);
							String sql="update tb_send set receive_state='2' where send_toname='"+UserName+"' and send_date='"+date+"'";
							mdao.ChangeState(sql);
							printlnn(".");
						}
					}
				}else if(strr.startsWith("DELE ")&&step==5){
					int begin=str.indexOf(" ");
					String sub=str.substring(begin+1);
					if(sub.matches("\\d")){
						int deleNum=Integer.parseInt(sub);
						if(deleNum>=1&&deleNum<=list.size()){
							boolean flag;
							DeleteMail dele=new DeleteMail();
							flag=dele.deleMail(fileName+"/"+ss[deleNum], basePath+"/"+UserName+"/delete/"+ss[deleNum]);
						    if(flag){
						    	int end=ss[deleNum].indexOf(".");
								String date=ss[deleNum].substring(0,end);
								String sql="update tb_send set receive_state='3' where send_toname='"+UserName+"' and send_date='"+date+"'";
								mdao.ChangeState(sql);
						    	printlnn("+OK core mail");
						    }
						}
					}
				}else if(strr.startsWith("QUIT")){
					printlnn("+OK cor mail");
					break;
				}else{
					printlnn("551 error");
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				pw.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public List<String> getFilesList(){
		List<String> lists=new ArrayList<String>();
		fileName=basePath+"/"+UserName+"/receive";
		File file=new File(fileName);
		File []files=file.listFiles();   
		for(File f:files){
//			System.out.println(f.getName());
			lists.add(f.getName());
		}
		return lists;
	}
	
	private void printlnn(String msg){
		pw.println(msg);
		pw.flush();
	}
	
}
